package com.yonyou.cyxdms.sysmanage.client.config;

import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * feiginClient传递header
 *
 * @author: houkaihua
 * @since: 2018/10/16
 * @updateDate:
 * @updateRemark:
 * @version:1.0 Copyright: Copyright (c) 2018
 */
@Component
public class FeiginHeaderManageConfig implements RequestInterceptor {

    private Logger logger = LoggerFactory.getLogger(com.yonyou.cyxdms.framework.config.FeiginHeaderConfig.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {

        /**
         * feign传递header
         */
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs != null) {
            HttpServletRequest request = attrs.getRequest();
            String url  = requestTemplate.request().url();
            if(url.indexOf("/api/guc")>=0||url.indexOf("/open/guc")>=0){
                return;
            }

            Enumeration<String> headerNames = request.getHeaderNames();
            requestTemplate.header(HttpHeaders.AUTHORIZATION,request.getHeader(HttpHeaders.AUTHORIZATION));
        }

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if (loginInfoDto != null) {
            //不打印了logger.debug("feigin之间调用，传递LoginInfoDto:{}", loginInfoDto);
            Map<String, Object> paramMap = new HashMap<>();
            try {
                paramMap = ApplicationContextHelper.beanToMap(loginInfoDto);
            } catch (IOException e) {
                logger.error("bean转Map失败", e);
            }
            //不打印了logger.debug("header中的数据：{}", JSONUtil.objectToJson(paramMap));
            if (MapUtils.isNotEmpty(paramMap)) {
                for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                    String values = param.getValue() == null ? null : String.valueOf(param.getValue());
                    requestTemplate.header(param.getKey(), values);
                }
                requestTemplate.header("userAgent", loginInfoDto.getLoginWay());
            }
        }
    }
}